package com.itjeffrey.autocode.common;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.itjeffrey.autocode.enums.ExceptionEnum;
import com.itjeffrey.autocode.exception.ACException;
import com.itjeffrey.autocode.util.ACBaseUtil;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.text.MessageFormat;
import java.util.Date;

/**
 * 通用异常返回类
 *
 * @From: Jeffrey
 * @Date: 2020/11/8
 */
@Data
public class Result<T> {

    //错误码
    private Integer errCode;

    //错误信息
    private String errMsg;

    //数据
    private T data;

    //日期时间，@JsonFormat() 获取date日期按照指定格式进行格式化输出
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
    private Date dateTime;

    //静态方式调用
    public static <T> Result<T> ok() {
        return ok(HttpStatus.OK.value(), "SUCCESS", null);
    }

    public static <T> Result<T> ok(T data) {
        return ok(HttpStatus.OK.value(), "SUCCESS", data);
    }

    public static <T> Result<T> ok(String msg, T data) {
        return ok(HttpStatus.OK.value(), msg, data);
    }

    public static <T> Result<T> ok(Integer errCode, String errMsg, T data) {
        return new Result<>(errCode, errMsg, data);
    }

    public static <T> Result<T> fail(ExceptionEnum exceptionEnum) {
        return new Result<>(exceptionEnum);
    }

    public static <T> Result<T> fail(Integer errCode, String errMsg) {
        return new Result<>(errCode, errMsg, null);
    }

    public static <T> Result<T> fail(Integer errCode, String errMsg, T data) {
        return new Result<>(errCode, errMsg, data);
    }

    public Result() {
        this.errCode = 200;
        this.errMsg = "SUCCESS";
        this.dateTime = new Date();
    }

    public Result(T data) {
        this.errCode = 200;
        this.errMsg = "SUCCESS";
        this.data = data;
        this.dateTime = new Date();
    }

    public Result(String msg, T data) {
        this.errCode = 200;
        this.errMsg = msg;
        this.data = data;
        this.dateTime = new Date();
    }

    public Result(Integer code, String msg, T data) {
        this.errCode = code;
        this.errMsg = msg;
        this.data = data;
        this.dateTime = new Date();
    }

    public Result(ACException exception) {
        this.errCode = exception.getErrCode();
        this.errMsg = exception.getErrMsg();
        this.dateTime = new Date();
    }

    public Result(ExceptionEnum exceptionEnum) {
        this.errCode = exceptionEnum.getErrorCode();
        this.errMsg = exceptionEnum.getErrorMessage();
        this.dateTime = new Date();
    }

    //基于可变参数的异常返回
    public Result(ExceptionEnum exceptionEnum, String... args) {
        this.errCode = exceptionEnum.getErrorCode();
        String errorMessage = exceptionEnum.getErrorMessage();
        String formatStr = ACBaseUtil.formatMessage(errorMessage, '{', '}');
        String formatMessage = MessageFormat.format(formatStr, args);
        this.errMsg = formatMessage;
        this.dateTime = new Date();
    }

}
